package main

import (
	"time"
	"math/rand"
	"match-spider/util/prop"
	"github.com/gocolly/colly"
	"fmt"
	"github.com/robertkrimen/otto"
	"match-spider/util/pg"
)
func fetchBifa(date string)  {
	url:="http://vip.win007.com/betfa/oddsData.aspx?date="+date

	c := colly.NewCollector()
	c.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

	c.OnResponse(func(response *colly.Response) {
		content:=string(response.Body)

		vm := otto.New()
		vm.Run(content)
		v,_:=vm.Get("B")
		list,_:=v.Export()
		sql := "insert into t_match_bf(match_id,jw_home,jw_draw,jw_guest,cjl_home,cjl_draw,cjl_guest,bl_home,bl_draw,bl_guest," +
			"bf_win,bf_draw,bf_lose,yk_home,yk_draw,yk_guest,created_at) values"
		size:=len(list.([][]string))
		for _, v := range list.([][]string) {
			data:=v
			if data==nil||len(data)==0{
				continue
			}

			at:=time.Now().Format("2006-01-02 15:04:05")


			sql += "("
			sql+=data[0]+","
			sql+=data[25]+","
			sql+=data[26]+","
			sql+=data[27]+","
			sql+=data[28]+","
			sql+=data[29]+","
			sql+=data[30]+","
			sql+=data[31]+","
			sql+=data[32]+","
			sql+=data[33]+","
			sql+=data[34]+","
			sql+=data[35]+","
			sql+=data[36]+","
			sql+=data[37]+","
			sql+=data[38]+","
			sql+=data[39]+","
			sql+="'"+at+"'"
			sql += "),"


			//pg.Insert(sql,data[0],data[25],data[26],data[27],data[28],data[29],data[30],data[31],data[32],data[33],data[34],data[35],data[36],data[37],data[38],data[39],at)

		}

		if size > 0 {
			sql = sql[0 : len(sql)-1]
			pg.Insert(sql)
		}
	})
	c.OnRequest(func(r *colly.Request) {
		fmt.Println("Visiting", r.URL.String())
	})
	c.OnError(func(r *colly.Response, err error) {
		fmt.Println("Error Request URL:", r.Request.URL)

	})

	c.Visit(url)
}
func main()  {

	startAt:=prop.Get("match","date.start")
	endAt:=prop.Get("match","date.end")
	startTime,_:=time.Parse("2006-01-02",startAt)
	endTime,_:=time.Parse("2006-01-02",endAt)

	for{
		if(endTime.Sub(startTime).Hours()<0){
			break
		}

		nextTimeString:=time.Unix(startTime.Unix(),0).Format("2006-01-02")
		fetchBifa(nextTimeString)
		seed:=100+rand.Intn(300)
		time.Sleep(time.Millisecond*time.Duration(seed))
		startTime=startTime.Add(time.Hour*24)
	}
}
